import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';

export function run(): Promise<void> {
  // 创建Mocha实例
  const mocha = new Mocha({
    ui: 'tdd',
    color: true,
    timeout: 10000,
    reporter: 'mocha-multi-reporters',
    reporterOptions: {
      reporterEnabled: 'spec, xunit',
      xunitReporterOptions: {
        output: path.join(__dirname, '..', 'test-results.xml')
      }
    }
  });

  const testsRoot = path.resolve(__dirname, '..');

  return new Promise((resolve, reject) => {
    // 查找所有测试文件
    glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
      if (err) {
        return reject(err);
      }

      // 添加测试文件到Mocha
      files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));

      try {
        // 运行测试
        mocha.run(failures => {
          if (failures > 0) {
            reject(new Error(`${failures} tests failed.`));
          } else {
            resolve();
          }
        });
      } catch (err) {
        console.error(err);
        reject(err);
      }
    });
  });
}

// 直接运行测试时使用
if (require.main === module) {
  run().then(
    () => process.exit(0),
    err => {
      console.error('Test failures:', err);
      process.exit(1);
    }
  );
}